﻿using AnlianCommon.API.Commands.Personnels;
using AnlianCommon.Common.Domains.OrganizationalUnits;
using AnlianCommon.Common.Domains.UserPermissions;
using AnlianCommon.Common.DTO;
using AnlianCommon.Common.Infrastructure.IRepository;
using AnlianCommon.Enum;
using AutoMapper;
using MediatR;

namespace AnlianCommon.API.Commands.Departments
{
    public class DepartmentCreateHander : IRequestHandler<DepartmentCreateCommand, Result>
    {
        private readonly IMapper _mapper;
        private readonly IBaseRepository<Department> _departmentRepository;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="departmentRepository"></param>
        public DepartmentCreateHander(IMapper mapper, IBaseRepository<Department> departmentRepository)
        {
            _mapper = mapper;
            _departmentRepository = departmentRepository;
        }

        /// <summary>
        /// 添加部门信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(DepartmentCreateCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Added };
            try
            {
                var department = _mapper.Map<Department>(request);
                var list = await _departmentRepository.Add(department);
                if (list > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Msg = "添加成功";
                }
                else
                {
                    result.Msg = "添加失败";
                }
            }
            catch (Exception)
            {

                throw;
            }
            return result;
        }
    }
}
